<?php

// http://hcms.iuact.cc/iupay/demo/

header('Content-type: text/html; charset=utf-8');
//error_reporting(E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_WARNING);
ini_set('display_errors', true);

$config = require_once './config.php';
$openid = $_GET['openid'];
if(empty($openid)){
    $oauth_url = 'https://pay.iuact.cc/wechat/login?app_key='.$config['app_key'].'&sub_mch_id='.$config['sub_mch_id'].'&callback='.urlencode('http://'.$_SERVER['HTTP_HOST'].'/iupay/demo/?code=1');
    header('Location:'.$oauth_url);
    die;
}

include 'sdk/iupay.php';
$iupay = new IUPay($config);
$outTradeNo = date('YmdHis', time()).rand(100, 999);
$subject = 'hpking';
$totalFee = 1; // 单位：分
$extra = 'ass';

$response = $iupay->mp($outTradeNo, $subject, $totalFee, $openid, $extra);
//print_r($response);

$burl = 'http://'.$_SERVER['HTTP_HOST'].'/iupay/demo/backurl.php?out_trade_no='.$outTradeNo;

echo '<script>
    function onBridgeReady(){
        WeixinJSBridge.invoke(
        "getBrandWCPayRequest", {
            "appId":"'.$response['appId'].'",
            "timeStamp":"'.$response['timeStamp'].'",
            "nonceStr":"'.$response['nonceStr'].'",
            "package":"'.$response['package'].'",
            "signType":"'.$response['signType'].'",
            "paySign":"'.$response['sign'].'"
        },
        function(res){
            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                alert("支付成功");
                window.location.href = "'.$burl.'";
            }
        });
    }
    if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
            document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
        }else if (document.attachEvent){
            document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
            document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
        }
    }else{
        onBridgeReady();
    }
</script>';

